﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using STSdb.General.Collections;
using STSdb.General.Buffers;

namespace STSdb.Persist
{
    public class PrimitiveStringIndexerPersist : IIndexerPersist<String>
    {
        public void Store(BinaryWriter writer, IIndexer<string> values)
        {
            byte[] buffer = new byte[(int)Math.Ceiling(values.Count / 8.0)];

            string[] array = new string[values.Count];
            int length = 0;

            for (int i = 0; i < values.Count; i++)
            {
                string value = values[i];
                if (value != null)
                {
                    buffer.SetBit(i, 1);
                    array[length++] = value;
                }
                //else
                //    buffer.SetBit(i, 0);
            }

            writer.Write(buffer);

            for (int i = 0; i < length; i++)
                writer.Write(array[i]);
        }

        public void Load(BinaryReader reader, IIndexer<string> values)
        {
            byte[] buffer = reader.ReadBytes((int)Math.Ceiling(values.Count / 8.0));

            for (int i = 0; i < values.Count; i++)
                values[i] = buffer.GetBit(i) == 1 ? reader.ReadString() : null;
        }
    }
}
